#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <pthread.h>
#include "tq.h"
#include "devinfo.h"

// 函数声明
const char* find_system_chinese_font_debug();
int load_font_debug(FT_Library library, const char* path, FT_Face* face, const char* type);


// 图片结构体
typedef struct {
    int width;
    int height;
    unsigned char *data;
} Image;

// GIF动画结构体
typedef struct {
    int frame_count;
    int *delays;  // 每帧延迟时间(毫秒)
    Image **frames; // 各帧图像
    int current_frame;
    time_t last_frame_time;
} Animation;

// 函数声明
void free_image(Image *img); // 添加 free_image 的前向声明
Image *load_png(const char *filename);
Animation *load_and_resize_gif(const char *filename, int width, int height);
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <linux/fb.h>
#include <time.h>
#include <ft2build.h>
#include <png.h>
#include <gif_lib.h>
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include "stb_image_resize2.h"
#include FT_FREETYPE_H
#include <dirent.h>
#define VOLUME_MIN 0
#define VOLUME_MAX 63
#include <cjson/cJSON.h>

extern int in_time_mode ;
extern int battery_capacity;
extern int vol_capacity;
extern char capacity_str[32];   // 当前控制状态(1=显示,0=隐藏)
extern char battery_status[32]; // 上次控制状态
extern char capacity_str_vol[32]; // 上次控制状态





// 控制文件操作函数
static inline void init_control_file() {
    // Create /tmp/var directory if it doesn't exist
    mkdir("/run/lock", 0777);
    
    // Check/create showtime.cid file with initial value 1
    FILE *cid_file = fopen("/run/lock/showtime.cid", "r");
    if (!cid_file) {
        cid_file = fopen("/run/lock/showtime.cid", "w");
        if (cid_file) {
            fprintf(cid_file, "1");
            fclose(cid_file);
        }
    } else {
        fclose(cid_file);
    }
}

static inline int should_exit_from_control_file() {
    // 使用更低级别的文件操作提高响应速度
    int fd = open("/run/lock/showtime.cid", O_RDONLY);
    if (fd < 0) {
        return 0; // 文件不存在时默认不退出
    }

    char buf[2] = {0};
    read(fd, buf, 1);
    close(fd);

    // 确保文件内容为'0'时才返回退出状态
    
    if (read_battery_status(battery_status, &battery_capacity) == 0) {
        snprintf(capacity_str, sizeof(capacity_str), "电量:%d%%", battery_capacity);
    } else {
        strcpy(battery_status, "Unknown");
        strcpy(capacity_str, "N/A");
    }
    // 读取音量状态
    
    vol_capacity = get_current_volume_s();
    snprintf(capacity_str_vol, sizeof(capacity_str_vol), "音量:%d%%", vol_capacity);
    //printf("无法加载图片: 1.png%d,%d",vol_capacity,battery_capacity);

    return (buf[0] == '0') ? 1 : 0;
}

// 帧缓冲结构体
typedef struct {
    int fd;
    char *map;
    struct fb_var_screeninfo var_info;
    int width;
    int height;
    int bpp;
    int bytes_per_pixel;
    long screen_size;
    char *back_buffer;
} FrameBuffer;

// 字体渲染结构体
typedef struct {
    FT_Library library;
    FT_Face face;
    FT_Face chinese_face;  // 新增中文字体
} FontRenderer;


// 天气数据结构体
typedef struct {
    float temperature;
    float humidity;
    char data_info[32];  // 新增天气数据
    char city[64];
    char img[64];  // 存储天气图标文件名
    time_t last_update;
    pthread_mutex_t lock;
    char last_icon_path[256]; // 上次加载的图标路径
    Image *cached_icon;       // 缓存的图标
} WeatherData;

// 全局数据
extern WeatherData global_weather;
extern Animation *global_animation;
extern Image *global_charging_icon; // 充电图标
extern Image *global_battery_icon;  // 电池图标
extern Image *global_wsd_icon;      // 温湿度传感器图标
extern int current_control_state;   // 当前控制状态
extern int last_control_state;      // 上次控制状态
// 初始化天气数据
void weather_init(WeatherData *weather) {
    memset(weather, 0, sizeof(WeatherData));
    pthread_mutex_init(&weather->lock, NULL);
    weather->temperature = 0;
    weather->humidity = 0;
    strcpy(weather->data_info, "晴天");
    weather->last_update = 0;
    strcpy(weather->city, "北京");
}

// 清理天气数据
void weather_cleanup(WeatherData *weather) {
    pthread_mutex_destroy(&weather->lock);
}


cJSON* json_get(cJSON* root, const char* path) {
    char* copy = strdup(path);
    char* token = strtok(copy, ".");
    cJSON* current = root;
    
    while (token && current) {
        current = cJSON_GetObjectItemCaseSensitive(current, token);
        token = strtok(NULL, ".");
    }
    
    free(copy);
    return current;
}


// 天气更新线程函数
// 初始化软件配置
static char* init_soft() {
    // 加载程序启动时需要的静态图片
    global_charging_icon = load_png("1.png");
    if (!global_charging_icon) {
        printf("无法加载图片: 1.png\n");
        // 考虑是否需要错误处理或返回
    }
    global_battery_icon = load_png("2.png");
    if (!global_battery_icon) {
        printf("无法加载图片: 2.png\n");
        // 考虑是否需要错误处理或返回
    }
    global_wsd_icon = load_png("wsdcgq.png");
    if (!global_wsd_icon) {
        printf("无法加载图片: wsdcgq.png\n");
        // 考虑是否需要错误处理或返回
    }
    int wi = 50;
    int hi = 50;
    global_animation = load_and_resize_gif("animation.gif", wi, hi);
    if (!global_animation) {
        printf("无法加载图片: animation.gif\n");
        // 考虑是否需要错误处理或返回
    }
    
    static char city_code[32] = "WgwUa"; // 默认北京
    
    // 尝试读取配置文件
    FILE *fp = fopen("/etc/akutq_city.conf", "r");
    if (fp) {
        char line[128];
        while (fgets(line, sizeof(line), fp)) {
            if (strncmp(line, "city_code=", 10) == 0) {
                strncpy(city_code, line+10, sizeof(city_code)-1);
                city_code[strcspn(city_code, "\r\n")] = '\0'; // 去除换行符
                break;
            }
        }
        fclose(fp);
    } else {
        // 文件不存在，创建配置文件
        printf("正在创建配置文件...\n");
        //mkdir("etc", 0755); // 确保etc目录存在
        fp = fopen("/etc/akutq_city.conf", "w");
        if (!fp) {
            printf("创建配置文件失败: %s\n", strerror(errno));
            return city_code;
        }
        
        printf("成功创建配置文件\n");
        fprintf(fp, "city_code=%s\n",city_code);
        fclose(fp);
    }



    return city_code;
}


void* weather_update_thread(void* arg) {
    WeatherData* weather = (WeatherData*)arg;
    tq* weather_api = tq_init(init_soft()); // 使用配置文件中的城市代码
    
    while (in_time_mode) {
            cJSON* weather_json = tq_v1(weather_api);
            if (weather_json) {
                // 打印原始JSON用于调试
                char *json_str = cJSON_Print(weather_json);
                //printf("原始天气JSON:\n%s\n", json_str);
                
                // 打印所有一级字段
                cJSON *item = weather_json->child;
                //printf("一级字段:\n");
                while (item) {
                    //printf("  %s (type: %d)\n", item->string, item->type);
                    item = item->next;
                }
                
                free(json_str);
            
            cJSON* img = json_get(weather_json, "data.real.weather.img");
            if (img && cJSON_IsString(img)) {
                printf("天气图标: %s\n", img->valuestring);
                char filename[256];
                snprintf(filename, sizeof(filename), "%s.png", img->valuestring);
                tq_down_png(weather_api, filename);
                
                // 更新天气图标文件名
                pthread_mutex_lock(&weather->lock);
                strncpy(weather->img, img->valuestring, sizeof(weather->img)-1);
                weather->img[sizeof(weather->img)-1] = '\0';
                pthread_mutex_unlock(&weather->lock);
            }
            
            // 调试打印温度湿度路径
            cJSON* temp = json_get(weather_json, "data.real.weather.temperature");
            cJSON* humidity = json_get(weather_json, "data.real.weather.humidity");
            cJSON* data_info = json_get(weather_json, "data.real.weather.info");
            // 尝试多种可能的城市名称路径
            cJSON* city = json_get(weather_json, "data.real.station.city");
            //printf("温度指针: %p, 湿度指针: %p\n", temp, humidity);
            
            
            pthread_mutex_lock(&weather->lock);
            
            if (temp) {
                weather->temperature = temp->valuedouble;
                //printf("获取到温度值: %.1f\n", weather->temperature);
            }
            if (humidity) {
                weather->humidity = humidity->valuedouble;
                //printf("获取到湿度值: %.1f\n", weather->humidity);
            }
            if (data_info) {
                if (cJSON_IsString(data_info)) {
                    strncpy(weather->data_info, cJSON_GetStringValue(data_info), sizeof(weather->data_info)-1);
                    weather->data_info[sizeof(weather->data_info)-1] = '\0';
                } else if (cJSON_IsNumber(data_info)) {
                    snprintf(weather->data_info, sizeof(weather->data_info), "%.1f", data_info->valuedouble);
                }
                //printf("获取到天气数据: %s\n", weather->data_info);
            }
            if (city && cJSON_IsString(city)) {
                printf("获取到城市名称: %s\n", cJSON_GetStringValue(city));
                strncpy(weather->city, cJSON_GetStringValue(city), sizeof(weather->city)-1);
                weather->city[sizeof(weather->city)-1] = '\0';
                printf("更新后的城市名称: %s\n", weather->city);
            } else {
                printf("未获取到有效的城市名称\n");
            }
            printf("城市: %s\n", weather->city);
            weather->last_update = time(NULL);
            pthread_mutex_unlock(&weather->lock);
            
            cJSON_Delete(weather_json);
        }
        
        // 每30分钟更新一次
        sleep(30 * 60);
    }
    
    tq_free(weather_api);
    return NULL;
}

// 初始化帧缓冲
int fb_init(FrameBuffer *fb, const char *device) {
    fb->fd = open(device, O_RDWR);
    if (fb->fd < 0) {
        perror("无法打开帧缓冲设备");
        return -1;
    }

    if (ioctl(fb->fd, FBIOGET_VSCREENINFO, &fb->var_info) < 0) {
        perror("无法获取屏幕信息");
        close(fb->fd);
        return -1;
    }

    fb->width = fb->var_info.xres;
    fb->height = fb->var_info.yres;
    fb->bpp = fb->var_info.bits_per_pixel;
    fb->bytes_per_pixel = fb->bpp / 8;
    fb->screen_size = fb->width * fb->height * fb->bytes_per_pixel;

    fb->map = mmap(NULL, fb->screen_size, PROT_READ | PROT_WRITE, MAP_SHARED, fb->fd, 0);
    if (fb->map == MAP_FAILED) {
        perror("无法映射帧缓冲");
        close(fb->fd);
        return -1;
    }

    // 分配后备缓冲区
    fb->back_buffer = malloc(fb->screen_size);
    if (!fb->back_buffer) {
        perror("无法分配后备缓冲区");
        munmap(fb->map, fb->screen_size);
        close(fb->fd);
        return -1;
    }

    printf("屏幕分辨率: %dx%d, 色深: %d位\n", fb->width, fb->height, fb->bpp);
    return 0;
}

// 关闭帧缓冲
void fb_close(FrameBuffer *fb) {
    if (fb->back_buffer) free(fb->back_buffer);
    if (fb->map) munmap(fb->map, fb->screen_size);
    if (fb->fd >= 0) close(fb->fd);
}

// 在后备缓冲区写入像素
void fb_write_pixel(FrameBuffer *fb, int x, int y, unsigned char r, unsigned char g, unsigned char b) {
    // 垂直翻转
    int mirrored_y = fb->height - 1 - y;
    
    if (x >= 0 && x < fb->width && mirrored_y >= 0 && mirrored_y < fb->height) {
        long pos = (mirrored_y * fb->width + x) * fb->bytes_per_pixel;
        
        if (fb->bpp == 16) {
            // RGB565格式
            unsigned short rgb565 = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
            *((unsigned short*)(fb->back_buffer + pos)) = rgb565;
        } else {
            // 假设32位色BGRA格式
            fb->back_buffer[pos] = b;
            fb->back_buffer[pos+1] = g;
            fb->back_buffer[pos+2] = r;
            fb->back_buffer[pos+3] = 0xFF; // Alpha通道
        }
    }
}

// 绘制直线
void fb_draw_line(FrameBuffer *fb, int x0, int y0, int x1, int y1, unsigned char r, unsigned char g, unsigned char b) {
    int dx = abs(x1 - x0);
    int dy = abs(y1 - y0);
    int sx = x0 < x1 ? 1 : -1;
    int sy = y0 < y1 ? 1 : -1;
    int err = dx - dy;
    
    while (1) {
        fb_write_pixel(fb, x0, y0, r, g, b);
        if (x0 == x1 && y0 == y1) break;
        int e2 = 2 * err;
        if (e2 > -dy) {
            err -= dy;
            x0 += sx;
        }
        if (e2 < dx) {
            err += dx;
            y0 += sy;
        }
    }
}

// 绘制圆
void fb_draw_circle(FrameBuffer *fb, int x0, int y0, int radius, unsigned char r, unsigned char g, unsigned char b) {
    int x = radius;
    int y = 0;
    int err = 0;

    while (x >= y) {
        fb_write_pixel(fb, x0 + x, y0 + y, r, g, b);
        fb_write_pixel(fb, x0 + y, y0 + x, r, g, b);
        fb_write_pixel(fb, x0 - y, y0 + x, r, g, b);
        fb_write_pixel(fb, x0 - x, y0 + y, r, g, b);
        fb_write_pixel(fb, x0 - x, y0 - y, r, g, b);
        fb_write_pixel(fb, x0 + y, y0 - x, r, g, b);
        fb_write_pixel(fb, x0 + x, y0 - y, r, g, b);

        if (err <= 0) {
            y += 1;
            err += 2*y + 1;
        }
        if (err > 0) {
            x -= 1;
            err -= 2*x + 1;
        }
    }
}

// 绘制矩形
void fb_draw_rect(FrameBuffer *fb, int x, int y, int width, int height, unsigned char r, unsigned char g, unsigned char b) {
    // 绘制四条边
    fb_draw_line(fb, x, y, x + width, y, r, g, b); // 上边
    fb_draw_line(fb, x, y + height, x + width, y + height, r, g, b); // 下边
    fb_draw_line(fb, x, y, x, y + height, r, g, b); // 左边
    fb_draw_line(fb, x + width, y, x + width, y + height, r, g, b); // 右边
}

// 填充矩形
void fb_fill_rect(FrameBuffer *fb, int x, int y, int width, int height, unsigned char r, unsigned char g, unsigned char b) {
    for (int i = 0; i < height; i++) {
        fb_draw_line(fb, x, y + i, x + width, y + i, r, g, b);
    }
}

// 修改字体加载函数，添加权限检查
int load_font_with_permission_check(FT_Library library, const char* font_path, FT_Face* face) {
    // 检查文件是否存在
    if (access(font_path, F_OK) != 0) {
        //fprintf(stderr, "字体文件不存在: %s\n", font_path);
        return -1;
    }
    
    // 检查文件可读权限
    if (access(font_path, R_OK) != 0) {
        //fprintf(stderr, "无读取字体文件权限: %s\n", font_path);
        return -1;
    }
    
    // 尝试加载字体
    int error = FT_New_Face(library, font_path, 0, face);
    if (error) {
        //fprintf(stderr, "字体加载失败(错误代码 %d): %s\n", error, font_path);
        return -1;
    }
    
    return 0;
}
// 查找系统字体目录中的中文字体


int font_init(FontRenderer *fr, const char *font_path) {
    if (FT_Init_FreeType(&fr->library)) {
        fprintf(stderr, "FreeType初始化失败\n");
        return -1;
    }

    // 加载英文字体
    //printf("尝试加载字体: %s\n", font_path);
    if (load_font_with_permission_check(fr->library, font_path, &fr->face)) {
        FT_Done_FreeType(fr->library);
        return -1;
    }

    // 查找中文字体
    const char *chinese_font_path = find_system_chinese_font_debug();
    if (chinese_font_path == NULL) {
        printf("错误: 未找到系统内置中文字体\n");
        // 尝试使用项目目录下的中文字体
        chinese_font_path = "./simfang.ttf";
        printf("尝试使用项目字体: %s\n", chinese_font_path);
    }
    
    if (chinese_font_path) {
        printf("正在加载中文字体: %s\n", chinese_font_path);
        if (load_font_debug(fr->library, chinese_font_path, &fr->chinese_face, "中文") != 0) {
            printf("错误: 中文字体加载失败\n");
            fr->chinese_face = NULL;
        } else {
            printf("成功加载中文字体\n");
        }
    } else {
        fr->chinese_face = NULL;
    }

    return 0;
}
const char* find_system_chinese_font_debug() {
    const char* chinese_fonts[] = {
        "simfang.ttf",               // 黑体
        "HarmonyOS_Sans_SC_Regular.ttf",
        "NotoSansCJK-Regular.ttf",  // Google Noto字体
        "DroidSansFallback.ttf",    // Android字体
        "WenQuanYiMicroHei.ttf",    // 文泉驿微米黑
        "uming.ttc",                // 文鼎字体
        "ukai.ttc",                 // 文鼎字体
        "simsun.ttc",               // 宋体
        "msyh.ttf",                 // 微软雅黑
        "simhei.ttf",               // 黑体
        NULL
    };

    const char* font_dirs[] = {
        "./",               // 黑体
        "/usr/share/fonts/", "/usr/local/share/fonts/","/usr/share/fonts/truetype/noto/",
        "/usr/share/fonts/truetype/", "/usr/share/fonts/opentype/",
        "/opt/aku/xiaozhi/font/", "/usr/share/fonts/truetype/dejavu/",
        "/usr/share/fonts/TTF/", "/usr/share/fonts/OTF/",
        "/usr/local/share/fonts/truetype/", 
        "/usr/local/share/fonts/opentype/",
        NULL
    };

    printf("\n=== 开始扫描系统字体 ===\n");
    
    for (int i = 0; font_dirs[i] != NULL; i++) {
        //printf("扫描目录: %s\n", font_dirs[i]);
        
        DIR *dir = opendir(font_dirs[i]);
        if (dir == NULL) {
            //printf("无法打开目录: %s\n", font_dirs[i]);
            continue;
        }

        struct dirent *entry;
        while ((entry = readdir(dir)) != NULL) {
            if (entry->d_type != DT_REG && entry->d_type != DT_LNK) 
                continue;
                
            for (int j = 0; chinese_fonts[j] != NULL; j++) {
                static char full_path[512];
                snprintf(full_path, sizeof(full_path), "%s%s", font_dirs[i], entry->d_name);

                //printf("搜索候选字体: %s\n", full_path);
                if (strstr(entry->d_name, chinese_fonts[j]) != NULL) {
                    static char full_path[512];
                    snprintf(full_path, sizeof(full_path), "%s%s", font_dirs[i], entry->d_name);
                    
                    //printf("找到候选字体: %s\n", full_path);
                    
                    // 检查文件权限
                    if (access(full_path, R_OK) == 0) {
                        //printf("字体可用: %s\n", full_path);
                        closedir(dir);
                        return full_path;
                    } else {
                        //printf("无读取权限: %s\n", full_path);
                    }
                }
            }
        }
        closedir(dir);
    }
    
    //printf("=== 扫描完成，未找到可用中文字体 ===\n");
    return NULL;
}

// 增强版字体加载函数
int load_font_debug(FT_Library library, const char* path, FT_Face* face, const char* type) {
    //printf("\n尝试加载%s字体: %s\n", type, path);
    
    if (access(path, F_OK) != 0) {
        //printf("错误: 文件不存在\n");
        return -1;
    }
    
    if (access(path, R_OK) != 0) {
        //printf("错误: 无读取权限\n");
        return -1;
    }
    
    int error = FT_New_Face(library, path, 0, face);
    if (error == FT_Err_Unknown_File_Format) {
        //printf("错误: 不支持的字体格式\n");
    } else if (error) {
        //printf("错误: 加载失败 (错误代码 %d)\n", error);
    } else {
        printf("成功加载 %s 字体\n", type);
        //printf("字体家族: %s\n", (*face)->family_name);
        //printf("字体样式: %s\n", (*face)->style_name);
        //printf("支持字符集: %d\n", (*face)->num_charmaps);
        
        // 打印支持的字符集
        for (int i = 0; i < (*face)->num_charmaps; i++) {
            FT_CharMap charmap = (*face)->charmaps[i];
            //printf("  - 编码: %d, 平台ID: %d, 编码ID: %d\n", 
            //      charmap->encoding, charmap->platform_id, charmap->encoding_id);
        }
    }
    
    return error;
}

// 增强版字体初始化
int font_init_debug(FontRenderer *fr, const char *font_path) {
    //printf("\n=== 初始化字体系统 ===\n");
    
    if (FT_Init_FreeType(&fr->library)) {
        //printf("错误: FreeType初始化失败\n");
        return -1;
    }
    //printf("FreeType初始化成功\n");

    // 加载主字体
    if (load_font_debug(fr->library, font_path, &fr->face, "主") != 0) {
        FT_Done_FreeType(fr->library);
        return -1;
    }

    // 查找并加载中文字体
    const char *chinese_path = find_system_chinese_font_debug();
    if (chinese_path) {
        if (load_font_debug(fr->library, chinese_path, &fr->chinese_face, "中文") != 0) {
            printf("警告: 中文字体加载失败，将使用主字体显示中文\n");
            fr->chinese_face = NULL;
        }
    } else {
        printf("警告: 未找到系统中文ttf字体\n");
        fr->chinese_face = NULL;
    }

    printf("=== 字体初始化完成 ===\n\n");
    return 0;
}
// 清空后备缓冲区
void fb_clear_back_buffer(FrameBuffer *fb, unsigned char r, unsigned char g, unsigned char b) {
    if (fb->bpp == 16) {
        unsigned short rgb565 = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
        unsigned short *p = (unsigned short*)fb->back_buffer;
        for (long i = 0; i < fb->width * fb->height; i++) {
            p[i] = rgb565;
        }
    } else {
        // 32位色
        for (long i = 0; i < fb->screen_size; i += 4) {
            fb->back_buffer[i] = b;
            fb->back_buffer[i+1] = g;
            fb->back_buffer[i+2] = r;
            fb->back_buffer[i+3] = 0xFF;
        }
    }
}

// 更新屏幕显示
void fb_update_screen(FrameBuffer *fb) {
    memcpy(fb->map, fb->back_buffer, fb->screen_size);
}



// 关闭字体渲染器
void font_close(FontRenderer *fr) {
    if (fr->face) FT_Done_Face(fr->face);
    if (fr->chinese_face) FT_Done_Face(fr->chinese_face);
    if (fr->library) FT_Done_FreeType(fr->library);
}

// 绘制文本（支持中文）
void draw_text(FrameBuffer *fb, FontRenderer *fr, const char *text, int x, int y, 
               unsigned char r, unsigned char g, unsigned char b, int font_size, int is_chinese) {
    FT_Face face = is_chinese ? fr->chinese_face : fr->face;
    FT_Set_Char_Size(face, 0, font_size * 64, 96, 96);
    
    int pen_x = x;
    int pen_y = y; // 直接使用传入的y坐标作为基线
    
    for (int i = 0; text[i] != '\0'; ) {
        unsigned long unicode_char;
        int char_len;
        
        // 判断是否是ASCII字符
        if ((text[i] & 0x80) == 0) {
            // ASCII字符
            unicode_char = text[i];
            char_len = 1;
        } else {
            // 中文字符（UTF-8编码）
            if ((text[i] & 0xE0) == 0xC0) {
                unicode_char = ((text[i] & 0x1F) << 6) | (text[i+1] & 0x3F);
                char_len = 2;
            } else if ((text[i] & 0xF0) == 0xE0) {
                unicode_char = ((text[i] & 0x0F) << 12) | ((text[i+1] & 0x3F) << 6) | (text[i+2] & 0x3F);
                char_len = 3;
            } else {
                // 不支持的编码，跳过
                i++;
                continue;
            }
        }
        
        if (FT_Load_Char(face, unicode_char, FT_LOAD_RENDER | FT_LOAD_TARGET_MONO)) {
            i += char_len;
            continue;
        }
        
        FT_GlyphSlot glyph = face->glyph;
        FT_Bitmap bitmap = glyph->bitmap;
        
        for (int row = 0; row < bitmap.rows; row++) {
            for (int col = 0; col < bitmap.width; col++) {
                int byte_pos = row * bitmap.pitch + col / 8;
                int bit_pos = 7 - (col % 8);
                int pixel = bitmap.buffer[byte_pos] & (1 << bit_pos);
                
                if (pixel) {
                    fb_write_pixel(fb, 
                                  pen_x + col + glyph->bitmap_left,
                                  pen_y - row + glyph->bitmap_top,
                                  r, g, b);
                }
            }
        }
        
        pen_x += glyph->advance.x >> 6;
        i += char_len;
    }
}

// 优化后的绘制带透明度图片函数
void draw_image(FrameBuffer *fb, Image *img, int x, int y) {
    // 检查边界，防止越界
    if (x < 0 || y < 0 || x + img->width > fb->width || y + img->height > fb->height) {
        return;
    }

    for (int py = 0; py < img->height; py++) {
        for (int px = 0; px < img->width; px++) {
            int pos = ((img->height - 1 - py) * img->width + px) * 4;
            unsigned char r = img->data[pos];
            unsigned char g = img->data[pos+1];
            unsigned char b = img->data[pos+2];
            unsigned char a = img->data[pos+3];
            
            if (a > 0) {
                // 对于完全透明像素，直接跳过
                if (a == 255) {
                    fb_write_pixel(fb, x + px, y + py, r, g, b);
                } else {
                    // 读取当前背景像素值
                    long bg_pos = ((fb->height - 1 - (y + py)) * fb->width + (x + px)) * fb->bytes_per_pixel;
                    unsigned char bg_r = fb->back_buffer[bg_pos+2];
                    unsigned char bg_g = fb->back_buffer[bg_pos+1];
                    unsigned char bg_b = fb->back_buffer[bg_pos];
                    
                    // 优化的Alpha混合计算
                    unsigned char final_r = (r * a + bg_r * (255 - a)) / 255;
                    unsigned char final_g = (g * a + bg_g * (255 - a)) / 255;
                    unsigned char final_b = (b * a + bg_b * (255 - a)) / 255;
                    
                    fb_write_pixel(fb, x + px, y + py, final_r, final_g, final_b);
                }
            }
        }
    }
}

// 释放图片资源
void free_image(Image *img) {
    if (img) {
        if (img->data) free(img->data);
        free(img);
    }
}

// 读取电池状态
int read_battery_status(char *status, int *capacity) {
    FILE *fp;
    
    // 读取充电状态
    fp = fopen("/sys/class/power_supply/axp20x-battery/status", "r");
    if (!fp) return -1;
    
    if (fgets(status, 32, fp) == NULL) {
        fclose(fp);
        return -1;
    }
    fclose(fp);
    
    // 去除换行符
    status[strcspn(status, "\n")] = '\0';
    
    // 读取电量百分比
    fp = fopen("/sys/class/power_supply/axp20x-battery/capacity", "r");
    if (!fp) return -1;
    
    if (fscanf(fp, "%d", capacity) != 1) {
        fclose(fp);
        return -1;
    }
    fclose(fp);
    
    return 0;
}

// 加载并缩放GIF动画
Animation* load_and_resize_gif(const char *filename, int target_width, int target_height) {
    int error = 0;
    GifFileType *gif = DGifOpenFileName(filename, &error);
    if (!gif) {
        printf("无法打开GIF文件: %s (错误: %d)\n", filename, error);
        return NULL;
    }

    if (DGifSlurp(gif) != GIF_OK) {
        printf("解析GIF失败: %s\n", filename);
        DGifCloseFile(gif, &error);
        return NULL;
    }

    // 创建动画对象
    Animation *anim = malloc(sizeof(Animation));
    if (!anim) {
        DGifCloseFile(gif, &error);
        return NULL;
    }

    anim->frame_count = gif->ImageCount;
    anim->frames = malloc(anim->frame_count * sizeof(Image*));
    anim->delays = malloc(anim->frame_count * sizeof(int));
    anim->current_frame = 0;
    anim->last_frame_time = 0;

    if (!anim->frames || !anim->delays) {
        if (anim->frames) free(anim->frames);
        if (anim->delays) free(anim->delays);
        free(anim);
        DGifCloseFile(gif, &error);
        return NULL;
    }

    // 处理每一帧
    for (int f = 0; f < anim->frame_count; f++) {
        SavedImage *frame = &gif->SavedImages[f];
        GifImageDesc *desc = &frame->ImageDesc;
        GraphicsControlBlock gcb;
        DGifSavedExtensionToGCB(gif, f, &gcb);

        // 设置帧延迟时间(毫秒)
        anim->delays[f] = gcb.DelayTime * 10; // GIF单位是1/100秒

        // 创建原始图像缓冲区
        unsigned char *src_data = malloc(desc->Width * desc->Height * 4);
        if (!src_data) {
            // 清理已分配的资源
            for (int i = 0; i < f; i++) {
                free_image(anim->frames[i]);
            }
            free(anim->frames);
            free(anim->delays);
            free(anim);
            DGifCloseFile(gif, &error);
            return NULL;
        }

        // 转换GIF帧到RGBA
        ColorMapObject *cmap = (desc->ColorMap ? desc->ColorMap : gif->SColorMap);
        for (int i = 0; i < desc->Width * desc->Height; i++) {
            GifByteType color_idx = frame->RasterBits[i];
            GifColorType color = cmap->Colors[color_idx];
            src_data[i*4] = color.Red;
            src_data[i*4+1] = color.Green;
            src_data[i*4+2] = color.Blue;
            src_data[i*4+3] = (color_idx == gif->SBackGroundColor) ? 0 : 255; // 透明处理
        }

        // 创建目标图像缓冲区
        unsigned char *dst_data = malloc(target_width * target_height * 4);
        if (!dst_data) {
            free(src_data);
            // 清理已分配的资源
            for (int i = 0; i < f; i++) {
                free_image(anim->frames[i]);
            }
            free(anim->frames);
            free(anim->delays);
            free(anim);
            DGifCloseFile(gif, &error);
            return NULL;
        }

        // 手动实现简单的双线性缩放
        float x_ratio = (float)(desc->Width - 1) / target_width;
        float y_ratio = (float)(desc->Height - 1) / target_height;
        
        for (int y = 0; y < target_height; y++) {
            for (int x = 0; x < target_width; x++) {
                int src_x = (int)(x * x_ratio);
                int src_y = (int)(y * y_ratio);
                float x_diff = (x * x_ratio) - src_x;
                float y_diff = (y * y_ratio) - src_y;
                
                int src_pos = (src_y * desc->Width + src_x) * 4;
                int dst_pos = (y * target_width + x) * 4;
                
                // 双线性插值
                for (int c = 0; c < 4; c++) {
                    unsigned char a = src_data[src_pos + c];
                    unsigned char b = src_data[src_pos + 4 + c];
                    unsigned char c_val = src_data[src_pos + desc->Width * 4 + c];
                    unsigned char d = src_data[src_pos + desc->Width * 4 + 4 + c];
                    
                    unsigned char val = (unsigned char)(
                        a * (1 - x_diff) * (1 - y_diff) +
                        b * x_diff * (1 - y_diff) +
                        c_val * y_diff * (1 - x_diff) +
                        d * x_diff * y_diff
                    );
                    dst_data[dst_pos + c] = val;
                }
            }
        }

        free(src_data);

        // 创建图像对象
        Image *img = malloc(sizeof(Image));
        if (!img) {
            free(dst_data);
            // 清理已分配的资源
            for (int i = 0; i < f; i++) {
                free_image(anim->frames[i]);
            }
            free(anim->frames);
            free(anim->delays);
            free(anim);
            DGifCloseFile(gif, &error);
            return NULL;
        }

        img->width = target_width;
        img->height = target_height;
        img->data = dst_data;
        anim->frames[f] = img;
    }

    DGifCloseFile(gif, &error);
    return anim;
}


// 加载PNG图片（使用libpng库）
Image* load_png(const char *filename) {
    FILE *fp = fopen(filename, "rb");
    if (!fp) {
        fprintf(stderr, "无法打开PNG文件: %s\n", filename);
        return NULL;
    }

    png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (!png) {
        fclose(fp);
        return NULL;
    }

    png_infop info = png_create_info_struct(png);
    if (!info) {
        png_destroy_read_struct(&png, NULL, NULL);
        fclose(fp);
        return NULL;
    }

    if (setjmp(png_jmpbuf(png))) {
        png_destroy_read_struct(&png, &info, NULL);
        fclose(fp);
        return NULL;
    }

    png_init_io(png, fp);
    png_read_info(png, info);

    Image *img = malloc(sizeof(Image));
    if (!img) {
        png_destroy_read_struct(&png, &info, NULL);
        fclose(fp);
        return NULL;
    }

    img->width = png_get_image_width(png, info);
    img->height = png_get_image_height(png, info);
    img->data = malloc(img->width * img->height * 4);

    png_set_expand(png);
    png_set_strip_16(png);
    png_set_gray_to_rgb(png);
    png_set_add_alpha(png, 0xff, PNG_FILLER_AFTER);
    png_read_update_info(png, info);

    png_bytep *row_pointers = malloc(sizeof(png_bytep) * img->height);
    for (int y = 0; y < img->height; y++) {
        row_pointers[y] = (png_bytep)(img->data + y * img->width * 4);
    }

    png_read_image(png, row_pointers);
    png_read_end(png, NULL);

    free(row_pointers);
    png_destroy_read_struct(&png, &info, NULL);
    fclose(fp);

    return img;
}

// 获取中文星期名称
const char* get_chinese_weekday(int wday) {
    static const char* weekdays[] = {
        "周日", "周一", "周二", "周三", "周四", "周五", "周六"
    };
    if (wday >= 0 && wday < 7) {
        return weekdays[wday];
    }
    return "?";
}
// 读取音量
int get_current_volume_s(void) {
    FILE *fp;
    char cmd[128];
    char result[32];
    int volume = 0;
    
    // 使用amixer命令获取当前音量
    snprintf(cmd, sizeof(cmd), "amixer get 'Power Amplifier' | grep 'Mono:' | awk '{print $2}'");
    fp = popen(cmd, "r");
    if (fp) {
        if (fgets(result, sizeof(result), fp)) {
            volume = atoi(result);
        }
        pclose(fp);
    }
    
    // 确保音量在有效范围内
    if (volume < VOLUME_MIN) volume = VOLUME_MIN;
    if (volume > VOLUME_MAX) volume = VOLUME_MAX;

    return volume;
}

// 显示天气信息
void display_weather(FrameBuffer *fb, FontRenderer *fr, WeatherData *weather) {
    if (!weather) {
        printf("警告: weather指针为空\n");
        return;
    }

    // 只有当有更新时才显示天气
    pthread_mutex_lock(&weather->lock);
    if (weather->last_update == 0) {
        pthread_mutex_unlock(&weather->lock);
        return;
    }
    pthread_mutex_unlock(&weather->lock);

    float temp = 0, humidity = 0;
    int y_pos = 100;  // 从顶部向下偏移100像素
    int x_pos = fb->width - 150;  // 从右侧向左偏移150像素
    time_t last_update = 0;
    char current_img[64] = {0};
    
    // 获取天气数据
    pthread_mutex_lock(&weather->lock);
    temp = weather->temperature;
    humidity = weather->humidity;
    last_update = weather->last_update;
    strncpy(current_img, weather->img, sizeof(current_img)-1);
    current_img[sizeof(current_img)-1] = '\0';
    pthread_mutex_unlock(&weather->lock);

    // 检查是否需要更新图标
    if (strcmp(current_img, weather->last_icon_path) != 0 || weather->cached_icon == NULL) {
        // 释放旧图标
        if (weather->cached_icon) {
            free_image(weather->cached_icon);
            weather->cached_icon = NULL;
        }
        
        // 加载新图标
        char icon_path[256];
        snprintf(icon_path, sizeof(icon_path), "weather_icons/%s.png", current_img);
        weather->cached_icon = load_png(icon_path);
        
        // 更新最后加载的图标路径
        strncpy(weather->last_icon_path, current_img, sizeof(weather->last_icon_path)-1);
        weather->last_icon_path[sizeof(weather->last_icon_path)-1] = '\0';
    }

    // 绘制天气图标
    if (weather->cached_icon) {
        draw_image(fb, weather->cached_icon,  120, 102);
    }

    char temp_str[32];
    char humidity_str[32];
    char update_str[32];
    struct tm *tm_info = localtime(&last_update);
    
    snprintf(temp_str, sizeof(temp_str), "%.1f°C", temp);
    snprintf(humidity_str, sizeof(humidity_str), "%.1f%%", humidity);
    // 显示天气信息
    strftime(update_str, sizeof(update_str), "更新: %H:%M", tm_info);
    
    // 显示在屏幕右上角
    
    // 使用更醒目的颜色
    int r = 255;
    int g = 255;
    int b = 255;
    if  (temp>28){
        r=255;
        g=0;
        b=0;
    } else if (temp<18){
        r=255;
        g=255;
        b=0;
    } else{
        r=0;
        g=255;
        b=0;
    }
    draw_text(fb, fr, "温:"    ,     32, 17, 255, 255, 255, 9, 1);  // 黄色
    draw_text(fb, fr, temp_str    , 46, 17, r, g, b, 9, 0);  // 黄色

    if  (humidity>80){
        r=255;
        g=0;
        b=0;
    } else if (humidity<30){
        r=255;
        g=255;
        b=0;
    } else{
        r=0;
        g=255;
        b=0;
    }
    draw_text(fb, fr, "湿:",         32, 3 , 255, 255, 255, 9, 1);  // 青色
    draw_text(fb, fr, humidity_str, 46, 3 , r, g, b, 9, 0);  // 青色
    
    // 显示天气数据
    //char data_str[32];
    //snprintf(data_str, sizeof(data_str), "%s", weather->data_info);

    draw_text(fb, fr, weather->data_info, 130, 90, 255, 255, 255, 9, 1);
    

    
    
    
    // 显示城市名 (白字)
    char city_str[64];
    pthread_mutex_lock(&weather->lock);
    strncpy(city_str, weather->city, sizeof(city_str)-1);
    city_str[sizeof(city_str)-1] = '\0';
    pthread_mutex_unlock(&weather->lock);
    
    // 计算城市名字符长度(每个字符12像素)
    int city_len = strlen(city_str)/2 * 12;

    fb_fill_rect(fb, 3, 93, city_len+2, 20, 0, 255, 0);
    
    draw_text(fb, fr, city_str, 5, 95, 255, 255, 255, 12, 1);
    

    //draw_text(fb, fr, update_str, x_pos, y_pos + 50, 200, 200, 200, 10, 0);  // 灰色
}

// 内部实现函数
static int _show_time_and_battery_impl(FrameBuffer *fb, FontRenderer *fr, int *should_exit, WeatherData *weather) {

    time_t now;
    struct tm *tm_now;
    char time_str[6];
    char time_str_s[3];
    char date_str[11];
    
    // 定义颜色
    unsigned char low_color_r = 255, low_color_g = 0, low_color_b = 0;    // 红色 (<10%)
    unsigned char mid_color_r = 255, mid_color_g = 255, mid_color_b = 0;  // 黄色 (10%-80%)
    unsigned char high_color_r = 0, high_color_g = 255, high_color_b = 0;  // 绿色 (>80%)
    
    

    
    if (*should_exit) {
        return 0;
    }
        now = time(NULL);
        tm_now = localtime(&now);
        
        strftime(time_str, sizeof(time_str), "%H:%M", tm_now);
        strftime(time_str_s, sizeof(time_str_s), "%S", tm_now);
        strftime(date_str, sizeof(date_str), "%m-%d", tm_now);
        const char* weekday_str = get_chinese_weekday(tm_now->tm_wday);

        // 清屏后再绘制
        fb_clear_back_buffer(fb, 0, 0, 0);
        
        // 绘制时间
        // 绘制时间 (调整y坐标使文字左下角对齐)
        draw_text(fb, fr, time_str, 0, 50, 255, 255, 255, 40, 0);
        char sec1[2] = {time_str_s[0], '\0'};
        char sec2[2] = {time_str_s[1], '\0'};
        draw_text(fb, fr, sec1, 146, 64, 0, 255, 0, 12, 0);
        draw_text(fb, fr, sec2, 146, 52, 0, 255, 0, 12, 0);
        
        // 绘制日期和星期 (调整y坐标使文字左下角对齐)
        draw_text(fb, fr, date_str, 0, 35, 255, 255, 255, 12, 0);
        draw_text(fb, fr, weekday_str, 58, 35, 255, 255, 255, 9, 1);
        
        // 读取电池状态

        
        // 绘制时间
        
        // 绘制电池状态 (右上角)
        
        // 根据电量百分比选择颜色
        unsigned char r, g, b;
        if (battery_capacity < 10) {
            r = low_color_r;
            g = low_color_g;
            b = low_color_b;
        } else if (battery_capacity > 80) {
            r = high_color_r;
            g = high_color_g;
            b = high_color_b;
        } else {
            r = mid_color_r;
            g = mid_color_g;
            b = mid_color_b;
        }
        
        // 绘制电量百分比
        draw_text(fb, fr, capacity_str,     60,  90, r, g, b, 9, 1);
        draw_text(fb, fr, capacity_str_vol, 60, 110, r, g, b, 9, 1);
        
        // 如果是充电状态，在坐标(0,60)显示充电图标
        if (strcmp(battery_status, "Charging") == 0 && global_charging_icon) {
            draw_image(fb, global_charging_icon, 0, 115);
        }
        
    // 显示天气信息
    if (weather) {
        
        display_weather(fb, fr, weather);
    }
        draw_image(fb, global_wsd_icon, 0, 0);
        if (global_animation && global_animation->frames && global_animation->frame_count > 0) {
            static long last_anim_check = 0;
            struct timespec ts;
            clock_gettime(CLOCK_MONOTONIC, &ts);
            long current_ms = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
            
            // 每20ms检查一次动画帧切换，提高平滑度
            if (current_ms - last_anim_check >= 20) {
                last_anim_check = current_ms;
                
                // 计算帧间隔时间(毫秒)，确保最小50ms
                long frame_delay = global_animation->delays[global_animation->current_frame];
                if (frame_delay <= 0) frame_delay = 50; // 默认50ms
                
                // 检查是否需要切换到下一帧
                if (current_ms - global_animation->last_frame_time >= frame_delay) {
                    // 使用双缓冲技术减少闪烁
                    static Image* prev_frame = NULL;
                    
                    // 只清除动画区域，使用背景色填充
                    fb_fill_rect(fb, 100, 0, 
                               global_animation->frames[0]->width, 
                               global_animation->frames[0]->height, 
                               0, 0, 0);
                    
                    // 更新帧索引
                    prev_frame = global_animation->frames[global_animation->current_frame];
                    global_animation->current_frame = (global_animation->current_frame + 1) % global_animation->frame_count;
                    global_animation->last_frame_time = current_ms;
                    
                    // 绘制当前帧
                    draw_image(fb, global_animation->frames[global_animation->current_frame], 100, 0);
                    
                    // 立即更新屏幕
                    fb_update_screen(fb);
                }
            }
        }
        
        fb_update_screen(fb);
        
        // 睡眠到下一秒开始
    }


// 显示时间和电池状态
// 返回1表示继续显示，0表示退出
int show_time_and_battery_with_weather(FrameBuffer *fb, FontRenderer *fr, int *should_exit, WeatherData *weather) {
    return _show_time_and_battery_impl(fb, fr,  should_exit, weather);
}
